import Taro from '@tarojs/taro'
import { store } from '../store'

// 获取token
export function fetchToken() {
  return Taro.login()
    .then(({ code }) => Taro.request({
      // eslint-disable-next-line no-undef
      url: API_HOST + '/weapp/login',
      method: 'POST',
      data: { code },
      header: {
        'client': 'miniProgram',
        'content-type': 'application/json'
      }
    })).then(({ data: { data: { token } } }) => {
      Taro.setStorageSync('Authorization', token)
      return token
    })
}

// 检查session有效性
export function checkSession() {
  const token = Taro.getStorageSync('Authorization')
  if (token) {
    Taro.checkSession({
      success: () => { },
      fail: () => {
        fetchToken()
      }
    })
  }
}

export function checkAuth(cb, canBack = true){
  const {userInfo} = store.getState().app
  console.log('userInfo', userInfo)
  if (!userInfo.phoneNumber || !userInfo.avatarUrl) {
    // if(!canBack) {
    //   Taro.navigateTo({ url: `/pages/login/index?canBack=${false}` })
    //   return
    // }
    Taro.showModal({
      title: '提示',
      content: '更多功能需要用户授权',
      success: function (res) {
        if (res.confirm) {
          Taro.navigateTo({ url: '/pages/login/index' })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    return
  }
  cb()
}
